package gk.gkapi.rnd.reflection;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MainTest {

	public static Map<String, ?> getMethods(Class<?> aClass) throws IntrospectionException {
		Map<String, Object> mm = new HashMap<String, Object>();
		PropertyDescriptor pds[] = Introspector.getBeanInfo(aClass).getPropertyDescriptors();
		for (PropertyDescriptor pd : pds) {
			if (pd.getReadMethod() != null && !"class".equals(pd.getName())) {
				Method method = pd.getReadMethod();
				String key = pd.getName().intern();
				if (method.getReturnType().isPrimitive() || Comparable.class.isAssignableFrom(method.getReturnType())) {
					mm.put(key, pd.getReadMethod());
				} else {
					mm.put(key, getMethods(method.getReturnType()));
				}
			}
		}

		return mm;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String args[]) throws IllegalArgumentException, IntrospectionException,
			IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
		AddressBean ab = new AddressBean();
		ab.setCity("DEL");
		Map<String, Method> map = (Map<String, Method>) getMethods(AddressBean.class);

		int SIZE = 1000000;

		long stime = System.currentTimeMillis();
		for (int i = 0; i < SIZE; ++i) {
			ab.getCity();
		}
		long etime = System.currentTimeMillis();
		System.out.println(etime - stime);

		stime = System.currentTimeMillis();
		for (int i = 0; i < SIZE; ++i) {
			map.get("city").invoke(ab);
		}
		etime = System.currentTimeMillis();

		System.out.println(etime - stime);
	}

}
